// 导入Vue VueRouter
import Vue from "vue";
import VueRouter from "vue-router";

// 引入组件
import Home from "../views/Home.vue";
import Login from "../views/Login.vue";
import Index from "../components/index.vue";
import Commodity from "../components/Commodity.vue";
import ManageMent from "../components/ManageMent.vue";
import DocumentOne from "../components/DocumentOne.vue";
import DocumentTwo from "../components/DocumentTwo.vue";

const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    name: "home",
    component: Home,
    redirect: "/index",
    children: [
      {
        path: "/index",
        name: "index",
        component: Index,
        meta: { title: "首页" },
      },
      {
        path: "/commodity",
        name: "commodity",
        component: Commodity,
        meta: { title: "商品列表" },
      },
      {
        path: "/ManageMent",
        name: "management",
        component: ManageMent,
        meta: { title: "商品管理" },
      },
      {
        path: "/documentone",
        name: "documentone",
        component: DocumentOne,
        meta: { title: "页面1" },
      },
      {
        path: "/documenttwo",
        name: "documenttwo",
        component: DocumentTwo,
        meta: { title: "页面2" },
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: Login,
    meta: { title: "登录页" },
  },
];

// 创建路由器实例
const router = new VueRouter({
  mode: "history",
  routes,
});
// 全局注册挂载
Vue.use(VueRouter);
// 导出路由对象
import {
  Message
} from 'element-ui'
// 那么如何检测token值丢失了之后我们的路由会自动跳转到登录页面
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径  from 从哪个路径跳转过来  next 一个函数，表示放行
  // // 获取token
  let token = window.localStorage.getItem("token");
  // 获取存储token的开始时间
  const tokenStartTime = window.localStorage.getItem("tokenStartTime");
  // 后台给出的token有效时间，一个星期 单位 是秒
  // 我们自己定义6天过期，让用户重新登录一下， 用户总不可能在一个页面挂机一天吧
  const timeOver = 2 * 24 * 3600 * 1000;
  // 当前时间
  let date = new Date().getTime();
  // 如果大于说明是token过期了
  if (date - tokenStartTime > timeOver) {
    token = null;
  }
  if (!token) {
    if (to.path === "/login") return next();
    console.log(this);
    Message.error("登录状态过期，请重新登录")
    return next("/login");
  } else if (to.path == "/login") {
    return next("/");
  }
  next();
});

// 解决路由重复 Uncaught (in promise)错误
const VueRouterPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(to) {
  return VueRouterPush.call(this, to).catch((err) => err);
};
export default router;
